from fastapi import FastAPI, Request, Depends
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import JSONResponse
import uvicorn
import logging
from pathlib import Path

from app.core.config import config
from app.routers import chat, admin, users
from app.database.session import init_database
from app.models.database import Base, engine

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 配置日志
logging.basicConfig(
    level=config.get('LOG_LEVEL', 'INFO'),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/app.log'),
        logging.StreamHandler()
    ]
)

app = FastAPI(
    title="Personal Home AI Models Change System",
    description="家庭多模型智能调度系统",
    version="1.0.0"
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# 包含路由
app.include_router(chat.router, prefix="/api/v1")
app.include_router(admin.router, prefix="/admin")
app.include_router(users.router, prefix="/api/v1")

@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logging.info("Personal Home AI Models Change System 正在启动...")
    init_database()
    logging.info("系统启动完成")

@app.get("/")
async def root(request: Request):
    """根路径"""
    return JSONResponse({
        "message": "Personal Home AI Models Change System",
        "version": "1.0.0",
        "docs_url": "/docs",
        "admin_url": "/admin"
    })

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "personal-home-ai"}

if __name__ == "__main__":
    uvicorn.run(
        "app.main:app",
        host=config.get('APP_HOST', '0.0.0.0'),
        port=config.get_int('APP_PORT', 8000),
        reload=config.get_bool('DEBUG', False)
    )